﻿@using viBook.Common
@using viBook.Models
@model Chapter
@{
    var totalCommentPage = (int)Math.Ceiling((double)Model.NumberOfComments / Constant.MaximunCommentPerChapter);
    totalCommentPage = totalCommentPage == 0 ? 1 : totalCommentPage;
    bool isShowNextButton = totalCommentPage > 1;
}
<script type="text/javascript">
function Comment() {
    return new Comment(0, "", "", "", 0, false, false, false);
}

function Comment(id, username, content, createdDate, vote, isVotedUp, isVotedDown, isReported) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        content: ko.observable(content),
        createdDate: ko.observable(createdDate),
        vote: ko.observable(vote),
        chapterId: ko.observable( @Model.Id ),
        isVotedUp: ko.observable(isVotedUp),
        isVotedDown: ko.observable(isVotedDown),
        isReported: ko.observable(isReported),
        voteUp: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("VoteUp", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.vote(parseInt(currentComment.vote()) + 1);
                            currentComment.isVotedUp(true);
                            currentComment.isVotedDown(false);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        voteDown: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("VoteDown", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.vote(parseInt(currentComment.vote()) - 1);
                            currentComment.isVotedDown(true);
                            currentComment.isVotedUp(false);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        reportContent: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("ReportComment", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.isReported(true);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        }
    };
}

function Picture(id, src, tagCollection) {
    return {
        id: id,
        src: ko.observable(src),
        tagCollection: ko.observableArray(tagCollection),
        onRenderTagCompleted: function(elements) {
            var tagIndicator = $(elements)[1];
            var contentDiv = $(elements)[4];
            $(tagIndicator).ready(function() {
                $(tagIndicator).hover(
                    function() {
                        $(contentDiv).toggle(100);
                    }, function() {
                        $(contentDiv).toggle(100);
                    });
            });
        }
    };
}

function Tag(positionStr, content) {
    var temp = positionStr.split("_");
    var top = parseInt(temp[0]);
    var left = parseInt(temp[1]);
    var width = parseInt(temp[2]);
    var height = parseInt(temp[3]);
    return {
        y: ko.observable(top + 'px'),
        x: ko.observable(left + 'px'),
        x2: ko.observable((left + width) + 'px'),
        w: ko.observable(width + 'px'),
        h: ko.observable(height + 'px'),
        content: ko.observable(content)
    };
}

function ContentTag(id, name, numberOfBooks) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        numberOfBooks: ko.observable(numberOfBooks)
    };
}


function TagMode(desc, value) {
    return {
        desc: ko.observable(desc),
        value: ko.observable(value)
    };
}

//TODO: leave this is 1 for now
var commentList = @CustomHelpers.ChapterCommentsToJavaScriptConverter(@Model.Comments.ToList(), 1) ,
    pictureList = @CustomHelpers.PagesToJavaScriptConverter(@Model.Pages.ToList()) ,
    contentTagList = @CustomHelpers.ContentTagsToJavaScriptConverter(@Model.Book.ContentTags.ToList()) ,
    availableTagModes = [new TagMode("Normal", "TagTemplate"), new TagMode("Hover", "TagTemplateHover"), new TagMode("Disable", "TagTemplateDisable")],
    viewmodel = {
        chapterId: @Model.Id ,
        userId: 1,// TODO: Hardcoded for now
        pictureCollection: ko.observableArray(pictureList),
        commentCollection: ko.observableArray(commentList),
        contentTagCollection: ko.observableArray(contentTagList),
        comment: ko.observable(new Comment()),
        commentPageNo: ko.observable(1),
        totalCommentPage: ko.observable( @totalCommentPage ),
        isShowPrevBtn: ko.observable(false),
        isShowNextBtn: ko.observable( @isShowNextButton.ToString().ToLower() ),
        numberOfComments: ko.observable( @Model.NumberOfComments ),
        numberOfLikes: ko.observable( @Model.NumberOfLikes ),
        availableTagModes: ko.observableArray(availableTagModes),
        selectedTagMode: ko.observable(availableTagModes[0]),
        isReported:ko.observable(@viBook.Helpers.Helpers.BooleanToJavascript(@Model.IsReported)),
        toggleSidebar: function() {
            $('#sideBar').slideToggle('slow');
            $('#button-toggle').toggleClass("active");
        },
        reportChapter: function() {
             $.ajax({
                    url: '@Url.Action("Report", "Chapters")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: viewmodel.chapterId, userId: 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.success) {
                            viewmodel.isReported(true);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        likeChapter: function() {
            $.ajax({
                    url: '@Url.Action("Like", "Chapters")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: viewmodel.chapterId, userId: 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.success) {
                            viewmodel.numberOfLikes(viewmodel.numberOfLikes() + 1);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        fetchNextCommentPage: function() {
            $.ajax({
                    url: '@Url.Action("FetchNextCommentPage", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo() + 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var listComment = [];
                            $(result.comments).each(function(index, item) {
                                listComment[index] = new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
                            });
                            viewmodel.commentCollection(listComment);
                            viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
                            viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                            viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        fetchPreviousCommentPage: function() {
            $.ajax({
                    url: '@Url.Action("FetchNextCommentPage", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo() - 1 }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var listComment = [];
                            $(result.comments).each(function(index, item) {
                                listComment[index] = new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
                            });
                            viewmodel.commentCollection(listComment);
                            viewmodel.commentPageNo(viewmodel.commentPageNo() - 1);
                            viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                            viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        postComment: function() {
            $.ajax({
                    url: '@Url.Action("Create", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ userId: viewmodel.userId, content: viewmodel.comment().content(), chapterId: viewmodel.chapterId }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            var addedComment = new Comment(
                                parseInt(result.id),
                                viewmodel.comment().username(),
                                viewmodel.comment().content(),
                                viewmodel.comment().createdDate(),
                                viewmodel.comment().vote(),
                                viewmodel.comment().isVotedUp(),
                                viewmodel.comment().isVotedUp(),
                                viewmodel.comment().isReported());
                            viewmodel.commentCollection.unshift(addedComment);
                            viewmodel.comment(new Comment());
                            viewmodel.numberOfComments(viewmodel.numberOfComments() + 1);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        cancelPostComment: function() {
            viewmodel.comment(new Comment());
        }
    };
ko.applyBindings(viewmodel);
</script>
